package fun.eliauk.shuatiba.job.cycle;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import fun.eliauk.shuatiba.esdao.QuestionEsDao;
import fun.eliauk.shuatiba.mapper.QuestionMapper;
import fun.eliauk.shuatiba.model.dto.question.QuestionEsDTO;
import fun.eliauk.shuatiba.model.entity.Question;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class IncSyncQuestionToEs {

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private QuestionEsDao questionEsDao;

    /**
     * 每分钟执行1次
     */
    public void run() {
        // 查询近5分钟内发生改变的数据
        int FIVE_MINUTES = 5;
        DateTime fiveMinutesAgo = DateUtil.offset(new Date(), DateField.MINUTE, FIVE_MINUTES);
        List<Question> questionList = questionMapper.listNeedSync(fiveMinutesAgo);
        if (questionList.isEmpty()) {
            log.info("question date no inc");
            return;
        }
        List<QuestionEsDTO> questionEsDTOS = questionList.stream()
                .map(QuestionEsDTO::objToDto)
                .collect(Collectors.toList());

        final int pageSize = 500;
        int total = questionEsDTOS.size();
        log.info("IncSyncQuestionToEs total {}", total);

        for (int i = 0; i < total; i += pageSize) {
            int end = Math.min(i + pageSize, total);
            List<QuestionEsDTO> subList = questionEsDTOS.subList(i, end);
            log.info("sync from {} to {}", i, end);
            questionEsDao.saveAll(subList);
        }
        log.info("IncSyncQuestionToEs end {}", total);
    }
}
